<?php


namespace app\admin\service;

use app\common\model\GoodsSku;
use think\Model;

class Goods extends Model
{

    protected $name='goods';

    public function wxapp(){
        return $this->belongsTo("app\common\model\Wxapp",'wxapp_id','wxapp_id');
    }
    /**
     * 关联商品分类表
     * @return \think\model\relation\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo('app\common\model\Category');
    }

    /**
     * 关联商品规格表
     * @return \think\model\relation\HasMany
     */
    public function sku()
    {
        return $this->hasMany('app\common\model\GoodsSku')->order(['goods_sku_id' => 'asc']);
    }
    /**
     * 关联商品规格关系表
     * @return \think\model\relation\BelongsToMany
     */
    public function specRel()
    {
        return $this->belongsToMany('app\common\model\SpecValue', 'GoodsSpecRel')->order(['id' => 'asc']);
    }
    /**
     * 关联商品图片表
     * @return \think\model\relation\HasMany
     */
    public function image()
    {
        return $this->hasMany('app\common\model\GoodsImage')->order(['id' => 'asc']);
    }
    /**
     * 获取商品列表
     * @param $param
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function getList($param)
    {
        // 商品列表获取条件
        $params = array_merge([
            'status' => -1,         // 商品状态
            'search' => '',         // 搜索关键词
            'sortType' => 'all',    // 排序类型
            'sortPrice' => false,   // 价格排序 高低
            'listRows' => 15,       // 每页数量
        ], $param);

        // 筛选条件
        $filter = [];

        $params['status'] > 0 && $filter['goods_status'] = $params['status'];
        !empty($params['search']) && $filter['goods_name'] = ['like', '%' . trim($params['search']) . '%'];
//        if (isset($query['search']) && !empty($query['search'])) {
//            $this->where('wxapp.wxapp_name|user.nickName', 'like', '%' . trim($query['search']) . '%');
//        }
        // 起始时间
        !empty($params['start_time']) && $this->where('create_time', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('create_time', '<', strtotime($params['end_time']) + 86400);

        // 执行查询
        $list = $this
            ->field(['*', '(sales_initial + sales_actual) as goods_sales'])
            ->with(['wxapp','image.file', 'sku'])
            ->where('is_delete', '=', 0)
            ->where($filter)
            ->order('create_time desc')
            ->paginate($params['listRows'], false, [
                'query' => \request()->request()
            ]);

        // 整理列表数据并返回
        return $this->setGoodsListData($list, true);
    }
    /**
     * 获取商品详情
     * @param $goodsId
     * @return \app\common\model\Goods
     */
    public static function detail($goodsId)
    {
        /* @var $model self */
        $model = (new static)->with([
            'category',
            'image.file',
            'sku.image',
            'spec_rel.spec',
        ])->where('goods_id', '=', $goodsId)
            ->find();

        if (empty($model)) {
            return $model;
        }
        // 整理商品数据并返回
        return $model->setGoodsListData($model, false);
    }
    /**
     * 设置商品展示的数据
     * @param $data
     * @param bool $isMultiple
     * @param callable $callback
     * @return mixed
     */
    protected function setGoodsListData($data, $isMultiple = true, callable $callback = null)
    {
        if (!$isMultiple) $dataSource = [&$data]; else $dataSource = &$data;
        // 整理商品列表数据
        foreach ($dataSource as &$goods) {
            // 商品主图
            $goods['goods_image'] = $goods['image'][0]['file_path'];
            // 商品默认规格
            $goods['goods_sku'] = $goods['sku'][0];
            // 回调函数
            is_callable($callback) && call_user_func($callback, $goods);
        }
        return $data;
    }

    /**
     * 获取当前商品总数
     * @param array $where
     * @return int|string
     * @throws \think\Exception
     */
    public function getGoodsTotal($where = [])
    {
        return $this->where('is_delete', '=', 0)->where($where)->count();
    }

    /**
     * 获取本日新增商品
     * @param $day
     * @return int|string
     * @throws \think\Exception
     */
    public function getGoodsTodayTotal($day){
        return $this->where('is_delete', '=', 0)->whereTime('create_time',$day)->count();
    }

    /**
     *  获取本月新增
     * @param $month
     * @return int|string
     * @throws \think\Exception
     */

    public function getGoodsMonthTotal($month){
        return $this->where('is_delete', '=', 0)->whereTime('create_time', $month)->count();
    }



    /**
     * 商品销售榜
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsRanking()
    {
        return db('order_goods')->alias('o_goods')
            ->field([
                'goods_id',
                'goods_name',
                'SUM(total_pay_price) AS sales_volume',
                'SUM(total_num) AS total_sales_num'
            ])
            ->join('order', 'order.order_id = o_goods.order_id')
            ->where('order.pay_status', '=', 20)
            ->where('order.order_status', '<>', 20)
            ->group('goods_id, goods_name')
            // order：此处按总销售额排序，如需按销量改为total_sales_num
            ->order(['sales_volume' => 'DESC'])
            ->limit(10)
            ->select();
    }

}